<template>
  <div class="teacher-courses">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ $t('teacherCourses.title') }}</span>
      </div>
      
      <el-table :data="courseList" style="width: 100%">
        <el-table-column prop="name" :label="$t('teacherCourses.courseName')"></el-table-column>
        <el-table-column prop="info" :label="$t('teacherCourses.courseInfo')"></el-table-column>
        <el-table-column prop="location" :label="$t('teacherCourses.location')"></el-table-column>
        <el-table-column :label="$t('teacherCourses.time')">
          <template slot-scope="scope">
            {{ scope.row.startTime }} - {{ scope.row.endTime }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('teacherCourses.date')">
          <template slot-scope="scope">
            {{ scope.row.startDate }} 至 {{ scope.row.endDate }}
          </template>
        </el-table-column>
        <el-table-column prop="selectedNum" :label="$t('teacherCourses.selectedNum')"></el-table-column>
        <el-table-column prop="maxNum" :label="$t('teacherCourses.maxNum')"></el-table-column>
        <el-table-column :label="$t('teacherCourses.operation')" width="150" v-if="!isMobile">
          <template slot-scope="scope">
            <el-button type="text" @click="viewStudents(scope.row)">{{ $t('teacherCourses.viewStudents') }}</el-button>
          </template>
        </el-table-column>
        <!-- 移动端操作列 -->
        <el-table-column :label="$t('teacherCourses.operation')" width="100" fixed="right" v-if="isMobile">
          <template slot-scope="scope">
            <el-popover
              placement="left"
              width="120"
              trigger="click">
              <div class="mobile-operation-buttons">
                <el-button type="text" @click="viewStudents(scope.row)">{{ $t('teacherCourses.viewStudents') }}</el-button>
              </div>
              <el-button slot="reference" type="primary" size="mini">
                {{ $t('teacherCourses.operation') }} <i class="el-icon-arrow-down"></i>
              </el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 学生名单对话框 -->
    <el-dialog 
      :title="currentCourse ? `${currentCourse.name} - ${$t('teacherCourses.studentList')}` : $t('teacherCourses.studentList')"
      :visible.sync="studentDialogVisible"
      width="800px">
      <div class="student-list-header" :class="{'mobile-student-list-header': isMobile}">
        <el-button 
          type="primary" 
          size="small" 
          @click="exportStudentList" 
          v-if="studentList.length > 0"
          :loading="exporting"
          class="export-button">
          <i class="el-icon-download"></i> <span class="button-text">{{ $t('teacherCourses.exportList') }}</span>
        </el-button>
      </div>
      
      <el-table :data="studentList" style="width: 100%">
        <el-table-column prop="id" :label="$t('teacherCourses.studentId')"></el-table-column>
        <el-table-column prop="name" :label="$t('teacherCourses.studentName')"></el-table-column>
        <el-table-column prop="telephone" :label="$t('teacherCourses.telephone')"></el-table-column>
        <el-table-column prop="mail" :label="$t('teacherCourses.email')"></el-table-column>
        <el-table-column :label="$t('teacherCourses.operation')" width="120" v-if="!isMobile">
          <template slot-scope="scope">
            <el-button 
              type="text" 
              class="danger-text"
              @click="handleRemoveStudent(scope.row)">
              {{ $t('teacherCourses.removeStudent') }}
            </el-button>
          </template>
        </el-table-column>
        <!-- 移动端操作列 -->
        <el-table-column :label="$t('teacherCourses.operation')" width="95" fixed="right" v-if="isMobile">
          <template slot-scope="scope">
            <el-popover
              placement="left"
              width="120"
              trigger="click">
              <div class="mobile-operation-buttons">
                <el-button 
                  type="text" 
                  class="danger-text"
                  @click="handleRemoveStudent(scope.row)">
                  {{ $t('teacherCourses.removeStudent') }}
                </el-button>
              </div>
              <el-button slot="reference" type="primary" size="mini">
                {{ $t('teacherCourses.operation') }} <i class="el-icon-arrow-down"></i>
              </el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container" v-if="studentList.length > 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="studentQuery.current"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="studentQuery.size"
          :layout="paginationLayout"
          :total="total">
        </el-pagination>
      </div>

      <div class="empty-text" v-else>
        {{ $t('teacherCourses.noStudents') }}
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import request from '@/utils/request'
import { exportFile } from '@/utils/exportHelper'

export default {
  name: 'TeacherCourses',
  data() {
    return {
      courseList: [],
      studentList: [],
      total: 0,
      currentCourse: null,
      studentDialogVisible: false,
      studentQuery: {
        current: 1,
        size: 10
      },
      isMobile: false,
      screenWidth: document.body.clientWidth,
      paginationLayout: "total, sizes, prev, pager, next, jumper",
      exporting: false
    }
  },
  computed: {
    userId() {
      return this.getUserId()
    },
    isUserAdmin() {
      return this.getUserRole() === 'admin'
    },
    isUserTeacher() {
      return this.getUserRole() === 'teacher'
    }
  },
  created() {
    this.getCourseList()
    this.checkScreenSize()
  },
  mounted() {
    window.addEventListener('resize', this.handleResize)
    this.checkScreenSize()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    ...mapGetters(['getUserId', 'getUserRole']),
    handleResize() {
      this.screenWidth = document.body.clientWidth
      this.checkScreenSize()
    },
    checkScreenSize() {
      this.isMobile = this.screenWidth < 768
      
      // 根据屏幕尺寸调整分页控件布局
      if (this.isMobile) {
        this.paginationLayout = "prev, pager, next"
      } else {
        this.paginationLayout = "total, sizes, prev, pager, next, jumper"
      }
    },
    async getCourseList() {
      try {
        const res = await request.get(`/course/teacher/${this.userId}`)
        this.courseList = res.data
      } catch (error) {
        this.$message.error('获取课程列表失败')
      }
    },
    formatTime(time) {
      if (!time) return ''
      return `${time.hour}:${time.minute}`
    },
    async viewStudents(course) {
      this.currentCourse = course
      this.studentDialogVisible = true
      this.studentQuery.current = 1
      await this.getStudentList()
    },
    async getStudentList() {
      try {
        const res = await request.get(`/course/${this.currentCourse.id}/students`)
        this.studentList = res.data
        this.total = res.data.length
      } catch (error) {
        this.$message.error('获取学生名单失败')
      }
    },
    async handleRemoveStudent(student) {
      try {
        await this.$confirm(this.$t('teacherCourses.confirmRemove'), this.$t('teacherCourses.tip'), {
          confirmButtonText: this.$t('teacherCourses.confirm'),
          cancelButtonText: this.$t('teacherCourses.cancel'),
          type: 'warning'
        })
        
        await request.delete(`/course/${this.currentCourse.id}/student/${student.id}`)
        this.$message.success(this.$t('teacherCourses.removeSuccess'))
        await this.getStudentList()
        await this.getCourseList() // 更新课程列表中的选课人数
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(this.$t('teacherCourses.removeFailed'))
        }
      }
    },
    handleSizeChange(val) {
      this.studentQuery.size = val
      this.getStudentList()
    },
    handleCurrentChange(val) {
      this.studentQuery.current = val
      this.getStudentList()
    },
    exportStudentList() {
      if (!this.currentCourse || !this.currentCourse.id) {
        this.$message.warning(this.$t('teacherCourses.selectCourseFirst'));
        return;
      }
      
      exportFile({
        url: `/course/${this.currentCourse.id}/export-students`,
        defaultFileName: `${this.currentCourse.name}_学生名单`,
        beforeExport: () => {
          this.exporting = true;
        },
        afterExport: () => {
          this.exporting = false;
        },
        fileType: 'csv'
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.teacher-courses {
  padding: 20px;
  
  .student-list-header {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
  
  .empty-text {
    text-align: center;
    color: #909399;
    padding: 30px 0;
  }
  
  .danger-text {
    color: #F56C6C;
  }

  .mobile-operation-buttons {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }

  .mobile-operation-buttons .el-button {
    margin-left: 0;
    margin-bottom: 8px;
    width: 100%;
    text-align: left;
  }

  .mobile-operation-buttons .el-button:last-child {
    margin-bottom: 0;
  }
}

@media screen and (max-width: 768px) {
  .el-table {
    width: 100%;
    font-size: 12px;
  }
  
  .el-button {
    padding: 7px 10px;
    font-size: 12px;
  }
}

.student-list-header {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-end;
}

.mobile-student-list-header {
  justify-content: stretch;
}

.mobile-student-list-header .export-button {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.button-text {
  margin-left: 5px;
}

@media screen and (max-width: 768px) {
  .el-dialog {
    width: 95% !important;
    margin: 10px auto !important;
  }
  
  .export-button {
    width: 100%;
  }
  
  .el-table {
    font-size: 12px;
  }
}
</style> 